package jveins;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Random;

import jveins.base.Wave;

public class VeinsAdapter{
	private HashMap<Integer,Wave> map; 
	private Random randNum;
	
	public VeinsAdapter(){
		map = new HashMap<Integer,Wave>();
		randNum = new Random();
		System.out.println("Java: Veins Adapater Initialized");
	}
	
	public Random random(){
		return randNum;
	}
	
	public native void messageToC(int id, String msg);
	
	public native void scheduleSelfMsg(int id, String msg);
	
	public void onBeacon(int id, String msg){
		map.get(id).onBeacon(msg);
	}
	
	public void onData(int id, String msg){
		map.get(id).onData(msg);
	}
	
	public void onSelfMsg(int id, short kind){
		System.out.println("Java: sendSelfMsg to id=" + id + " with msg: " + kind);
		map.get(new Integer(id)).onSelfMsg(kind);
	}
	
	public void registerEntity(String clazzName, int id){
		System.out.println("Java: Registering new entity with class=" + clazzName + " and id=" + id);
		Class<?> clazz;
		try {
			clazz = Class.forName(clazzName.replace('/', '.'));
			if(Wave.class.isAssignableFrom(clazz)){
				Constructor<?> ctor;
				ctor = clazz.getConstructor(VeinsAdapter.class, int.class);
				Object object = ctor.newInstance(new Object[] {this, id });
				map.put(new Integer(id), (Wave)object);
				//((Wave)object).init();
			}else{
				System.out.println("Class does not implement WAVE");
				System.exit(1);
			}
		} catch (ClassNotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}catch (NoSuchMethodException | SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}catch (InstantiationException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
